import json
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
import time
# import pyautogui
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
# import requests
import subprocess
import os
from pathlib import Path
import pandas as pd



def download_m3u8(file_name,url):
    # 本地保存的文件名
    local_filename = file_name
    # 发送 HTTP GET 请求
    with requests.get(url, stream=True) as r:
        # 检查请求是否成功
        r.raise_for_status()

        # 以二进制模式打开本地文件
        with open(local_filename, 'wb') as f:
            # 逐块读取响应内容并写入文件
            for chunk in r.iter_content(chunk_size=8192):
                if chunk:  # 过滤掉保持连接的空块
                    f.write(chunk)
    # print(f"文件已成功下载到 {local_filename}")

def download_video(file_name):
    print('{}.mp4下载'.format(file_name))
    file_name = os.path.join(Path.cwd(),file_name)
    command = 'ffmpeg -protocol_whitelist concat,file,http,https,tcp,tls,crypto -i "{}.m3u8" -c copy "{}.mp4"'.format(file_name,file_name)
    # 使用 subprocess.Popen() 执行指令，并设置 stdout 和 stderr 为 PIPE

    # process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    result = subprocess.run(command, capture_output=True, text=True)
    # # 实时输出 stdout 和 stderr
    # while True:
    #     # 读取一行输出（非阻塞）
    #     stdout_line = process.stdout.readline()
    #     stderr_line = process.stderr.readline()
        
    #     # 如果 stdout 有输出，则打印
    #     if stdout_line:
    #         sys.stdout.write(stdout_line)
    #         sys.stdout.flush()  # 确保立即输出到控制台
        
    #     # 如果 stderr 有输出，则打印（通常用于错误信息）
    #     if stderr_line:
    #         sys.stderr.write(stderr_line)
    #         sys.stderr.flush()  # 确保立即输出到控制台
        
    #     # 检查进程是否已完成
    #     if process.poll() is not None:
    #         # 进程已完成，退出循环
    #         break
    
    # # 等待进程完成并获取返回码（通常这一步是多余的，因为我们已经在循环中检查了）
    # returncode = process.wait()
    # 打印指令的输出
    print(result.stdout)
    # 如果指令执行失败（返回码不为0），则打印错误信息
    if result.returncode != 0:
        print(f"Error: {result.stderr}")
    print('下载完成')
    



def out(xpath):
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    html = driver.find_element(By.XPATH, xpath).get_attribute("outerHTML")
    with open('out.html','w', encoding='utf8') as wf:
        wf.write(html)

def sleep():
    time.sleep(0.5)

def shortsleep():
    time.sleep(0)

def longsleep():
    time.sleep(5)

def click(xpath):
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    button = driver.find_element(By.XPATH, xpath)
    button.click()
    shortsleep()

def wait(xpath,n=10):
    WebDriverWait(driver, n).until(EC.presence_of_element_located((By.XPATH, xpath)))

def exist(xpath):
    try:
        driver.find_element(By.XPATH, xpath)
    except:
        return False
    else:
        return True

def write(xpath, text):
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    inputTag = driver.find_element(By.XPATH, xpath)
    inputTag.clear()
    inputTag.send_keys(text)
    shortsleep()

def get_html(xpath):
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    html = driver.find_element(By.XPATH, xpath).get_attribute("outerHTML")
    return html

def get_value(xpath):
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    html = driver.find_element(By.XPATH, xpath).get_attribute("value")
    return html

def get_class(xpath):
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    html = driver.find_element(By.XPATH, xpath).get_attribute("class")
    return html

def get_text(xpath):
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    text = driver.find_element(By.XPATH, xpath).text
    return text

def switch(xpath):
    iframe = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, xpath)))
    driver.switch_to.frame(iframe)
    shortsleep()

def exist_dt(dt_name):
    driver.get('http://10.64.202.213/resource')
    driver.switch_to.default_content() #切换主页面
    click("/html/body/div[3]/div[1]/div/div[2]/ul/li[4]/a") ## 点击‘资源维护’
    ## 切换iframe
    switch('//*[@id="frame"]')
    ## 输入查询内容
    write('html/body/div[1]/section/div/form/div[1]/input', dt_name)
    ## 点击库表
    click("/html/body/div[1]/section/div/form/div[4]/select/option[2]")
    ## 点击查询
    click("/html/body/div[1]/section/div/form/div[6]/button[1]")
    sleep()
    x = get_html('//*[@id="list-table"]/tbody')
    def match():
        if '表中无数据存在' in x:
            return False
        for j in range(x.count('<tr')):
            if get_text('//*[@id="list-table"]/tbody/tr[{}]/td[2]'.format(j+1))==dt_name:
            # and get_text('//*[@id="list-table"]/tbody/tr[{}]/td[3]'.format(j+1))=='宁德市信息中心':
                return True
        return False
    return match()



def run(course_url):
    driver.maximize_window()
    print('登录aioc……')
    driver.get("https://www.91aioc.com/myCenter")
    # driver.execute_script("document.body.style.zoom='0.2'")
    time.sleep(1)
    write('//*[@id="input"]','15694345585')
    write('//*[@id="normal_login_password"]','056918')
    pyautogui.press('enter')
    time.sleep(5)
    print('进入课程页面……')
    driver.get(course_url)# 进入课程页面
    driver.execute_script("document.body.style.zoom='0.25'")
    time.sleep(5)
    click('//*[@id="app"]/div[1]/div[2]/div[1]/div/div[1]/div/div[2]/div[4]/button') # 点击开始学习
    time.sleep(2)
    print('获取课程列表……')
    # 获取课程标题列表
    text = get_html('//*[@id="app"]/div[1]/div[2]/div[1]/div/div[3]/div[2]/div[2]')
    titles = dict()
    soup = BeautifulSoup(text, 'html.parser')
    children = next(soup.children).children
    for child in children:
        title = child.find_all('h4')[0].text 
        titles[title]=list()
        for li in child.find_all('li'):
            if li.find_all('span')[1].text.strip() and '实训' not in li.find_all('span')[1].text:
                titles[title].append(li.find_all('span')[1].text)
    # print(json.dumps(titles, indent=4, ensure_ascii=False))
    jies = sum([v for v in titles.values()],[])
    for jie in jies:
        print(jie)
        # click('//span[text()="{}"]'.format(jie))
        click('//span[@data-v-2f95f1ca="" and text()="{}"]'.format(jie))
        n = driver.window_handles  # 这个时候会生成一个新窗口或新标签页的句柄，代表这个窗口的模拟driver
        driver.switch_to.window(n[-1])  # driver切换至最新生产的页面
        time.sleep(3)
        text = get_html('//*[@id="app"]/div[1]/div[1]/div[2]/div/div[1]/div[1]/div/ul')
        videos = list()
        videos_url = list()
        soup = BeautifulSoup(text, 'html.parser')
        for li in soup.find_all('li'):
            videos.append(li.find('span').text)
        for video in videos:
            click('//span[text()="{}"]'.format(video))
            time.sleep(2)
            performance_log = driver.get_log("performance")
            for packet in performance_log:
                message = json.loads(packet.get("message")).get("message")
                if "Network.responseReceived" in message['method']:
                    if 'm3u8' in str(message):
                        url = message['params']['response']['url']
                        if url[:url.find('?')] not in [v[:v.find('?')] for v in videos_url]:
                            videos_url.append(url)
                            if os.path.exists('{}.m3u8'.format(video)):
                                continue
                            download_m3u8('{}.m3u8'.format(video),url)
                            download_video(video)
        driver.close()
        driver.switch_to.window(n[0])

def login():
    write('//*[@id="form_item_username"]','kangfengjian')
    write('//*[@id="form_item_password"]','1995KMkfj@')
    click('/html/body/div[2]/div/div[2]/div/div[1]/div/div/div/div[2]/div/form/button')  # 点击登录
    time.sleep(3)
    
def dialogue(question):
    click('//*[@id="app"]/main/div[2]/main/div[1]/div[1]/button')  # 点击加号
    time.sleep(0.5)
    click('//*[@id="app"]/main/div[2]/main/div[1]/div[3]/div/div/ul/li[1]/span')  # 点击新建对话
    time.sleep(0.5)
    click('//*[@id="app"]/main/div[2]/main/div[2]/div[3]/div[1]/div/div/button[1]')  # 取消联网
    time.sleep(0.5)
    write('//*[@id="app"]/main/div[2]/main/div[2]/div[3]/div[1]/div/textarea',question)  # 填写问题
    time.sleep(0.5)
    click('//*[@id="app"]/main/div[2]/main/div[2]/div[3]/div[1]/div/div/button[3]')  # 点击发送
    while not exist('//*[@id="app"]/main/div[2]/main/div[2]/div[2]/div/div[2]/div[2]/div[@class="actions"]'):
        time.sleep(1)
    answer = get_text('//*[@id="app"]/main/div[2]/main/div[2]/div[2]/div/div[2]/div[2]/div[1]')
    return answer




if __name__ =='__main__':
    # 定义driver
    chrome_option = Options()
    chrome_option.set_capability("goog:loggingPrefs", {"performance": "ALL"})
    chrome_option.add_argument("--start-maximized")
    # chrome_option.add_argument("--headless")  # 无头模式，不打开浏览器窗口
    service = Service("./chromedriver-win64/chromedriver.exe")
    driver = webdriver.Chrome(service=service, options=chrome_option)
    driver.get("https://ihpsweb.cloud.inspur.com:1443/chat")
    login()
    data = pd.read_excel('评估测试题回答结果.xlsx',dtype=str)
    for i in data.index:
        if not pd.isnull(data.loc[i,'海若回答']):
            continue
        question = data.loc[i,'问题']
        print(i,question)
        answer = dialogue(question)
        print(answer)
        print('='*100)
        data.loc[i,'海若回答'] = answer
        data.to_excel('评估测试题回答结果.xlsx',index=False)